import List from "../models/list.model.js";

import { errorHandler } from "../utils/error.js";

export const test = (req, res) => {
  res.json({
    message: "Api route is working!",
  });
};

export const createList = async (req, res, next) => {
  try {
    const listing = await List.create(req.body);
    return res.status(201).json({
      listing,
    });
  } catch (error) {
    next(error);
  }
};

export const getList = async (req, res, next) => {
  try {
    const list = await List.find();
    return res.status(200).json({
      list,
    });
  } catch (error) {
    next(error);
  }
};

export const deleteList = async (req, res, next) => {
  const listing = await List.findByIdAndDelete(req.params.id);
  if (!listing) {
    return next(errorHandler(404, "Listing not found!"));
  }

  if (req.body.user !== listing.user) {
    return next(errorHandler(401, "You can only delete your own listings!"));
  }
  try {
    await List.findByIdAndDelete(req.params.id);
    res.status(200).json("Listing has been deleted!");
  } catch (error) {
    next(error);
  }
};
